#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include "includes.h"
#include <pthread.h>
int sockfd;
u8 send_buf[512] = "hello world!\n";
u8 recv_buf[512] = {0};
void Pthread_Send()
{
	while (1) {
		if(recv_buf[0]==0x35&&recv_buf[1]==0x35)
		{
			memset(recv_buf,0,sizeof(recv_buf));
			send(sockfd, send_buf, strlen(send_buf), 0);   // 向服务器发送信息
		}
	}
}
void Pthread_Recv()
{
	while (1) {
		recv(sockfd, recv_buf, sizeof(recv_buf), 0);// 接收数据
		printf("%s\n",recv_buf);
	}
}
int Tcp_Client_Init()
{
	pthread_t send_id,recv_id;
	u16 port = 8080;             // 服务器的端口号
	u8 *server_ip = "192.168.1.103";       // 服务器ip地址
    int ret;
	sockfd = socket(AF_INET, SOCK_STREAM, 0);      // 创建通信端点：套接字
	if (sockfd < 0) {
		perror("socket");
		exit(-1);
	}
	// 设置服务器地址结构体
	struct sockaddr_in server_addr;
	bzero(&server_addr, sizeof(server_addr)); // 初始化服务器地址
	server_addr.sin_family = AF_INET;   // IPv4
	server_addr.sin_port = htons(port); // 端口
	inet_pton(AF_INET, server_ip, &server_addr.sin_addr.s_addr);    // ip
	// 主动连接服务器
	int err_log = connect(sockfd, (struct sockaddr*) &server_addr,
			sizeof(server_addr));
	if (err_log != 0) {
		printf("connect failed!\n");
		close(sockfd);
		exit(-1);
	}
	ret = pthread_create(&send_id,  NULL, (void *)Pthread_Send,NULL);
		if(ret!=0)
		{
			printf("create send pthread failed!\n");
			exit(-1);
		}
	ret = pthread_create(&recv_id,  NULL, (void *)Pthread_Recv,NULL);
		if(ret!=0)
		{
			printf("create send pthread failed!\n");
			exit(-1);
		}
	return 0;
}
